<!--
*  2021-03-15
*  获取员工登录列表
-->
<!-- -->
<template>
  <div id="app" class="home" tabindex="1" ref="tabDiv">
    <!-- 头部导航 -->
    <div class="wrapper" ref="wrapper" :style="{ top: top }">
      <van-nav-bar title="扫描二维码" @click-left="onClickLogout">
        <template slot="left">
          <span>登出</span>
        </template>
        <template #right>
          <van-button type="warning" @click="clearCacheFn">更新</van-button>
          <van-button @click="config.show = true">设置</van-button>
        </template>
      </van-nav-bar>
      <div class="home-login">
        <div class="home-login__logo"></div>
        <div class="home-login__btns">
          <van-button type="primary" @click="openWin('process')">查看过程</van-button>
          <van-button type="info" @click="onClickLeft(2)">生产报工</van-button>
          <van-button type="warning" @click="onClickLeft(3)">杂活报工</van-button>
          <van-button type="danger" @click="onClickLeft(4)">坯布冻结</van-button>
          <van-button type="warning" @click="onClickLeft(5)">机台维保</van-button>
          <van-button type="warning" @click="onClickLeft(6)">人员呼叫</van-button>
          <van-button type="warning" @click="onClickLeft(7)">布头确认</van-button>
        </div>
      </div>
    </div>
    <p>版本号：v1.7.33</p>

    <van-dialog v-model="config.show" title="工位台设置" :show-cancel-button="true" :show-confirm-button="true" @cancel="config.show=false" @confirm="confirmConfigFn">
      <template #default>
        <van-field label="名称" v-model="config.name"></van-field>
        <van-field label="位置" v-model="config.area"></van-field>
      </template>
    </van-dialog>

    <!-- 呼叫组件 -->
    <call-worker v-if="showCallWorker" ref="callWorkerRef" :dep-id="depId" :show-call-btn="false" @close="showCallWorker = false"></call-worker>

    <!-- 布样确认组件 -->
    <weaving-check v-if="showWeavingCheck" ref="weavingCheckRef" @close="showWeavingCheck = false"></weaving-check>
  </div>
</template>

<script>
import {
  getCurStep,
  getTaskAccept,
  getCurTaskId,
} from "@/api/warping";
import { openWin, randomStr, deepCopy, getFloat } from "@/utils/index";
import { getLoginList, getLogin, getTaskStep } from "@/api/login";
import {
  removeInfo,
  getLoginInfo,
  removeLoginInfo,
  setInfo,
  getTableData,
  removeTableData,
  setWeight,
  setErrorWeight,
  setLoginInfo, setConfigData, getConfigData
} from "@/utils/auth";
import dayjs from "dayjs";
import CallWorker from "@/views/call-worker/App";
import WeavingCheck from "@/views/weaving-check/App";
import {SPLIT_BLANK, SPLIT_COMMA} from "@/utils/enum";

export default {
  name: "Home",
  components: {WeavingCheck, CallWorker},
  props: {
    depId: {
      type: String,
      default: "45",    //后端配置车间ID
    }
  },
  data() {
    return {
      value: "",
      timer: null,
      weight: "",
      code: "",
      lastTime: "",
      nextTime: "",
      lastCode: "",
      nextCode: "",
      resUrl: "",
      loading: false,
      top: 0,
      flag: true,
      time: null,
      currWeight: 0,
      ip: "",
      loginList: [],
      greyClothId: '',
      timeStr: '',

      scanFlag: 0,

      /* 配置 */
      config: {
        show: false,
        name: "",
        area: "",
      },

      /* 员工呼叫 */
      showCallWorker: false,

      /* 布样确认 */
      showWeavingCheck: false,
    };
  },
  watch: {
    // 监听ip
    ip(ip) {
      if (ip == "192.168.66.115") {
        this.onGetWeight();
      }
    },
  },
  created() {
    const that = this;
    removeInfo();
    if (process.env.NODE_ENV === "production") {
      that.$nextTick(() => {
        that.getUserIP((ip) => {
          that.ip = ip;
        });
        // 监听页面消失的时候，关掉页面就可以了
        window.api.addEventListener(
          {
            name: "viewdisappear",
          },
          function () {
            // clearInterval(that.time)
            that.time = null;
            window.api.closeWin();
          }
        );
      });
    } else {
      window.apiready = function () {
        that.getUserIP((ip) => {
          that.ip = ip;
        });
        // 监听页面消失的时候，关掉页面就可以了
        window.api.addEventListener(
          {
            name: "viewdisappear",
          },
          function () {
            // clearInterval(that.time)
            that.time = null;
            window.api.closeWin();
          }
        );
      };
    }
  },
  mounted() {
    const that = this;
    let configData = getConfigData();
    if(configData) {
      that.config.name = configData.name;
      that.config.area = configData.area;
    }
  },
  methods: {
    openWin,
    //更新清理
    clearCacheFn() {
      const that = this;
      window.api.clearCache(() => {
        that.$toast.success("更新成功");
        window.api.rebootApp();
      });
    },
    // 扫码
    onClickLeft(flag) {
      this.scanFlag = flag;
      this.loading = false;
      if (!this.loading) {
        // this.flag = bool;
        this.onWatchEnter();
        this.loading = true;
        this.resUrl == "";
        this.$toast({
          type: "loading",
          message: "请扫码",
          forbidClick: true,
          duration: 20000,
        });
      }
    },
    // 监听扫码时间
    onWatchEnter() {
      this.code = "";
      this.lastTime = "";
      this.nextTime = "";
      this.lastCode = "";
      this.nextCode = "";
      window.addEventListener("keydown", this.onClickKeydown);
    },
    // 监听事件
    onClickKeydown(e) {
      const that = this;
      that.$toast({
        type: "loading",
        message: "二维码解析中",
        forbidClick: true,
        duration: 20000,
      });
      if (window.event) {
        // IE
        that.nextCode = e.keyCode;
      } else if (e.which) {
        // Netscape/Firefox/Opera
        that.nextCode = e.which;
      }
      if (e.which === 13) {
        if (that.code.length < 3) return; // 手动输入的时间不会让code的长度大于2，所以这里只会对扫码枪有

        that.$toast.clear();

        if(that.scanFlag == 3 || that.scanFlag == 4 || that.scanFlag == 5 || that.scanFlag == 6 || that.scanFlag == 7) {
          // 扫员工二维码
          let code = that.code.replace(/Shift/g, "");
          let loginIndex = code.indexOf(",type=login,");
          if (loginIndex != -1) {
            // 扫登陆码
            let infos = code.split(",type=login,");
            getLogin({
              no: infos[0],
              pwd: infos[1],
              platform: 2,
              captcha: randomStr(),
            }, res => {
              this.$toast.clear();
              let userInfo = {
                accessToken: res.accessToken,
                userId: res.userId,
                platform: res.platform,
                secret: res.secret,
                roles: res.roles,
                permission: res.permission,
                no: res.userNo,
                realName: res.realName
              }
              setInfo(userInfo);
              setLoginInfo({
                no: infos[0],
                pwd: infos[1],
                loginTime: dayjs().valueOf()
              });
              if(that.scanFlag == 3) {
                openWin("odd-job-task");
              } else if(that.scanFlag == 4) {
                openWin("cloth-freeze");
              } else if(that.scanFlag == 5) {
                openWin("maintenance");
              } else if(that.scanFlag == 6) {
                that.showCallWorker = true;
                that.$nextTick(() => {
                  that.$refs.callWorkerRef.showWorkerPopFn();
                });
              } else if(that.scanFlag == 7) {
                if(res.permission.indexOf("050902") == -1) {
                  that.$toast.fail("没有权限");
                  return;
                }
                console.log("---->showWeavingCheck", that.showWeavingCheck);
                that.showWeavingCheck = true;
              }

              window.removeEventListener("keydown", that.onClickKeydown);
            });
          } else {
            that.$toast.fail("员工二维码异常");
          }
        } else if(that.scanFlag == 2) {    //生产报工
          that.resUrl = that.code.replace(/Shift/g, SPLIT_BLANK);
          that.$refs.tabDiv.focus();
          if (!that.$validURL(that.resUrl) && isNaN(Number(that.resUrl))) {
            if(that.code.startsWith("98,")) {    //新版织造生产码 98,craftId,taskId,craftDetailId
              const ids = that.code.substr(3).split(SPLIT_COMMA);
              that.resUrl = process.env.VUE_APP_YARN_URL + "/task_step/list_to_do_4_worker?taskId=" + ids[1];
              that.onClickBtn(ids[1], that.code);
              return;
            } else {
              that.$toast.fail("请扫生产码");
              return false;
            }
          }

          if (that.loading) {
            let taskId = "0";
            if (!that.$validURL(that.resUrl)) {
              that.greyClothId = deepCopy(that.resUrl);
              that.resUrl = process.env.VUE_APP_YARN_URL + "/task_step/list_to_do_4_worker_from_res?greyClothId=" + that.resUrl;
            } else {
              let index = that.resUrl.indexOf("taskId=");
              let lastIndex = that.resUrl.indexOf("&craftId=");
              taskId = that.resUrl.substr(index + 7, lastIndex == -1 ? that.resUrl.length - index - 7 : lastIndex - index - 7);
            }
            if (taskId != 0) {
              that.onClickBtn(taskId);
            } else {
              getCurTaskId({
                greyClothId: that.greyClothId,
              }, res => {
                taskId = res;
                that.onClickBtn(taskId);
              });
            }
          }
        }

        that.code = "";
        that.lastCode = "";
        that.lastTime = "";
        return;
      }
      that.nextTime = new Date().getTime();
      if (!that.lastTime && !that.lastCode) {
        if (that.timeStr === '') {
        that.timeStr = dayjs().valueOf()
        console.log(dayjs().valueOf(), '开始时间')
      }
        that.code += e.key;
      }
      if (
        that.lastCode &&
        that.lastTime &&
        that.nextTime - that.lastTime > 500
      ) {
        // 当扫码前有keypress事件时,防止首字缺失
        that.code = e.key;
      } else if (that.lastCode && that.lastTime) {
        that.code += e.key;
      }
      that.lastCode = that.nextCode;
      that.lastTime = that.nextTime;
    },
    //
    onClickBtn(taskId, scanCode) {
      const that = this;
      if (!getLoginInfo()) {
        // 获取到扫码枪输入的内容，跳转页面
        getLoginList("", function (res) {
          window.removeEventListener("keydown", that.onClickKeydown);
          that.loginList = res;
          openWin("login", {
            resUrl: that.resUrl,
            loginList: that.loginList,
            taskId: taskId,
            ip: that.ip,
            greyClothId: that.greyClothId,
            scanCode: scanCode,
          });
        });
      } else {
        let loginTime = getLoginInfo().loginTime;
        if (dayjs().valueOf() - loginTime < 86400000) {
          // 24小时免登陆
          if (taskId != 0) {
            that.onGetCurStep(taskId, scanCode);
          } else {
            // 先获取taskId
            that.onGetCurStep(taskId, scanCode);
          }
        } else {
          // 获取到扫码枪输入的内容，跳转页面
          getLoginList("", function (res) {
            window.removeEventListener("keydown", that.onClickKeydown);
            that.loginList = res;
            openWin("login", {
              resUrl: that.resUrl,
              loginList: that.loginList,
              taskId: taskId,
              ip: that.ip,
              greyClothId: that.greyClothId,
              scanCode: scanCode,
            });
          });
        }
      }
    },
    // 获取当前步骤
    onGetCurStep(taskId, scanCode) {
      const that = this;
      getCurStep(
        {
          taskId: taskId,
        },
        (res) => {
          if (res[0].stepNo === 3 && res[0].stepName == "验布报工") {
            getLogin(
              {
                no: getLoginInfo().no,
                pwd: getLoginInfo().pwd,
                platform: 2,
                captcha: randomStr(),
              },
              function (res) {
                let userInfo = {
                  accessToken: res.accessToken,
                  userId: res.userId,
                  platform: res.platform,
                  secret: res.secret,
                  roles: res.roles,
                };
                setInfo(userInfo);
                // 登录成功  扫码返回信息
                getTaskStep(
                  {
                    resUrl: that.resUrl,
                  },
                  (res) => {
                    // 报工
                    let params = {
                      stepId: res[0].id,
                      flowType: res[0].flowType,
                      resId: res[0].resId,
                      stepNo: res[0].stepNo,
                      taskId: res[0].taskId,
                      resUrl: res[0].resUrl,
                      nextResUrl: res[0].doingResUrl,
                      nextStepNo: res[0].nextStepNo,
                      todoResUrl: res[0].todoResUrl,
                      doingResUrl: res[0].doingResUrl,
                      stepName: res[0].stepName,
                      nextStepName: res[0].nextStepName,
                      qrCode: that.resUrl,
                      status: res[0].status,
                      title: res[0].title,
                    };
                    if (res[0].status === 1) {
                      // 接单
                      that.onGetTaskAccept(params);
                    } else {
                      // 已接单
                      openWin("checkCloth", params);
                    }
                  }
                );
              }
            );
          } else {
            // 修布重新打印  清除之前保留数据
            if (getTableData()) {
              removeTableData();
            }
            // 获取到扫码枪输入的内容，跳转页面
            getLoginList("", function (res) {
              window.removeEventListener("keydown", that.onClickKeydown);
              that.loginList = res;
              openWin("login", {
                resUrl: that.resUrl,
                loginList: that.loginList,
                taskId: taskId,
                ip: that.ip,
                greyClothId: that.greyClothId,
                scanCode: scanCode,
              });
            });
          }
        }
      );
    },
    // 接单
    onGetTaskAccept(params) {
      let obj = {
        stepNo: params.stepNo,
        taskId: params.taskId,
      };
      getTaskAccept(obj, () => {
        // 已接单
        openWin("checkCloth", params);
      });
    },
    // 验布退出登录
    onClickLogout() {
      if (getLoginInfo()) {
        this.$toast({
          type: "success",
          message: "登录信息已删除",
          duration: 1000,
          onClose: () => {
            removeLoginInfo();
          },
        });
      } else {
        this.$toast({
          type: "fail",
          message: "信息不存在",
          duration: 1000,
        });
      }
    },
    getUserIP(onNewIP) {
      let MyPeerConnection =
        window.RTCPeerConnection ||
        window.mozRTCPeerConnection ||
        window.webkitRTCPeerConnection;
      let pc = new MyPeerConnection({
        iceServers: [],
      });
      let noop = () => {};
      let localIPs = {};
      let ipRegex =
        /([0-9]{1,3}(\.[0-9]{1,3}){3}|[a-f0-9]{1,4}(:[a-f0-9]{1,4}){7})/g;
      let iterateIP = (ip) => {
        if (!localIPs[ip]) onNewIP(ip);
        localIPs[ip] = true;
      };
      pc.createDataChannel("");
      pc.createOffer()
        .then((sdp) => {
          sdp.sdp.split("\n").forEach(function (line) {
            if (line.indexOf("candidate") < 0) return;
            line.match(ipRegex).forEach(iterateIP);
          });
          pc.setLocalDescription(sdp, noop, noop);
        })
        .catch(() => {});
      pc.onicecandidate = (ice) => {
        if (
          !ice ||
          !ice.candidate ||
          !ice.candidate.candidate ||
          !ice.candidate.candidate.match(ipRegex)
        )
          return;
        ice.candidate.candidate.match(ipRegex).forEach(iterateIP);
      };
    },
    // 获取重量
    onGetWeight() {
      const that = this;
      var serial = window.api.require("serialPort");
      serial.examine(function (ret) {
        if (ret.code) {
          serial.openRead(
            {
              com: "/dev/ttyS3", //串口地址
              rate: 9600, //波特率
              delay: 500, //RX延时 此参数能让数据返回完整单位毫秒（具体设置大小自测）
              hex: false, //返回数据类型 false:text  true:hex
            },
            function (ret) {
              console.log(ret);
              if (ret.code && ret.data) {
                let respon = ret.data.replace(/\n\r/g, " ");
                serial.close(function (ret) {
                  let res = respon.split("=");
                  let resultWeight = [...new Set(res)].filter(
                    (item) => item !== ""
                  )[0];
                  that.currWeight = that.reverse_a_number(resultWeight).replace(/\b(0+)/gi, "");
                  if (getFloat(that.currWeight, 2) <= 20) {
                    that.$toast({
                      type: "success",
                      message: "重量已清零",
                      onClose: () => {
                        setWeight(0);
                        setErrorWeight(0);
                      },
                    });
                  } else {
                    setTimeout(() => {
                      that.onGetWeight();
                    }, 5000);
                  }
                  // 获取重量自动提交
                  if (ret.code) {
                    // 关闭
                    console.log("关闭成功");
                  }
                });
              }
            }
          );
        } else {
          that.$toast.clear();
          that.$toast.fail("协议打开失败，请手动填写重量");
        }
      });
    },
    // 反转数字
    reverse_a_number(n) {
      n = n + "";
      return n.split("").reverse().join("");
    },

    /* 确认配置 */
    confirmConfigFn() {
      const that = this;
      setConfigData(that.config);
    },
  },
};
</script>

<style scoped lang="scss">
.home {
  .wrapper {
    display: flex;
    flex-direction: column;
    align-items: center;
    position: relative;
    top: 0;
    .van-nav-bar__left,
    .van-nav-bar__right {
      span {
        font-size: 30px;
      }
    }
    .home-login {
      width: 100%;
      height: 800px;
      display: flex;
      flex-direction: column;
      align-items: center;
      position: relative;
      .home-login__logo {
        width: 200px;
        height: 200px;
        margin: 80px 0px;
        @include bg-image("./../../assets/img/fns");
      }
      .home-login__btns {
        width: 900px;
        display: flex;
        justify-content: center;
        flex-flow: wrap;
        .van-button {
          flex: 0 0 180px;
          height: 80px;
          margin: 10px;
          background: #07c160;
          border-radius: 2px;
          font-size: 32px;
          color: #ffffff;
          position: relative;
          z-index: 300;
          &:first-child {
            background: rgba(247, 181, 0, 1);
          }
          &:nth-child(2) {
            background: rgba(0, 161, 230, 1);
          }
          &:nth-child(3) {
            background: #07c160;
          }
          &:nth-child(4) {
            background: rgb(86, 134, 10);
          }
          &:nth-child(5) {
            background: rgb(161, 51, 11);
          }
          &:nth-child(6) {
            background: rgba(29, 122, 84, 0.63);
          }
          &:nth-child(7) {
             background: rgba(206, 84, 32, 0.63);
           }
        }
      }

      .home-input {
        width: 470px;
        height: 80px;
        line-height: 80px;
        // position: absolute;
        // bottom: 20px;
        // z-index: 120;
      }
    }
  }
  p {
    padding-left: 10px;
    position: fixed;
    bottom: 0;
    left: 50%;
    margin-left: -60px;
    line-height: 60px;
  }
}
</style>
